package com.jinke.api.modules.ums.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.jinke.api.common.api.CommonPage;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.modules.app.enums.ChannelStatus;
import com.jinke.api.modules.app.request.UserChannelPageRequest;
import com.jinke.api.modules.ums.mapper.UserChannelMapper;
import com.jinke.api.modules.ums.model.*;
import com.jinke.api.modules.ums.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 后台管理员管理Service实现类
 * Created by macro on 2018/4/26.
 */
@Slf4j
@Service
//@RequiredArgsConstructor
public class UserChannelServiceImpl extends ServiceImpl<UserChannelMapper, UserChannel> implements UserChannelService {

    /*private final UmsAdminService umsAdminService;
    private final ChannelService channelService;
    private final ChannelCarrierService channelCarrierService;
    private final ChannelPlatformService channelPlatformService;*/
    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private ChannelCarrierService channelCarrierService;
    @Autowired
    private ChannelPlatformService channelPlatformService;

    @Override
    public CommonResult<CommonPage<UserChannelPageVO>> pageList(UserChannelPageRequest request) {
        List<Integer> userIds = Lists.newArrayList();
        Map<Integer, UmsAdmin> umsAdminMap = Maps.newHashMap();
        boolean hasData = true;
        if (StrUtil.isNotBlank(request.getUserName())) {
            umsAdminMap = Optional.ofNullable(
                    umsAdminService.lambdaQuery()
                            .like(UmsAdmin::getUsername, request.getUserName())
                            //.eq(UmsAdmin::getStatus, ChannelStatus.ON) 取决于user_channel状态
                            .select(UmsAdmin::getId, UmsAdmin::getUsername)
                            .list()
            ).orElse(Lists.newArrayList()).stream().collect(Collectors.toMap(UmsAdmin::getId, Function.identity()));

            userIds = new ArrayList<>(umsAdminMap.keySet());
            if (userIds.isEmpty()) {
                hasData = false;
            }
        }
        // 根据用户名 找一个不存在的用户名
        if (!hasData) {
            // 可以直接返回
            return CommonResult.success(CommonPage.restPage(
                    new Page<UserChannelPageVO>()
                            .setTotal(0)
                            .setSize(request.getPageSize())
                            .setCurrent(request.getPageNum())
                            .setRecords(Lists.newArrayList())));
        }

        List<Integer> channelIds = Lists.newArrayList();
        Map<Integer, Channel> channelMap = Maps.newHashMap();
        if (StrUtil.isNotBlank(request.getChannelName())) {
            channelMap = Optional.ofNullable(
                    channelService.lambdaQuery()
                            .like(Channel::getChannelName, request.getChannelName())
                            //.eq(Channel::getStatus, ChannelStatus.ON) 取决于user_channel状态
                            .select(Channel::getId, Channel::getChannelName)
                            .list()).orElse(Lists.newArrayList()).stream().collect(Collectors.toMap(Channel::getId, Function.identity()));
            channelIds = new ArrayList<>(channelMap.keySet());
            if (channelIds.isEmpty()) {
                hasData = false;
            }
        }

        // 根据渠道名 找一个不存在的渠道
        if (!hasData) {
            // 可以直接返回
            return CommonResult.success(CommonPage.restPage(
                    new Page<UserChannelPageVO>()
                            .setTotal(0)
                            .setSize(request.getPageSize())
                            .setCurrent(request.getPageNum())
                            .setRecords(Lists.newArrayList())));
        }

        Page<UserChannel> userChannelPageList = Optional.ofNullable(
                this.page(
                        new Page<>(request.getPageNum(), request.getPageSize()),
                        Wrappers.<UserChannel>lambdaQuery()
                                .in(CollectionUtil.isNotEmpty(userIds), UserChannel::getUserId, userIds)
                                .in(CollectionUtil.isNotEmpty(channelIds), UserChannel::getChannelId, channelIds)
                                .select(UserChannel::getId, UserChannel::getUserId, UserChannel::getChannelId, UserChannel::getChannelCarrierId,
                                        UserChannel::getChannelPlatformId, UserChannel::getCreatedAt, UserChannel::getIsBest,
                                        UserChannel::getPlatformRate, UserChannel::getPrice, UserChannel::getRate))
        ).orElse(new Page<UserChannel>());

        List<UserChannel> userChannels = Optional.ofNullable(userChannelPageList.getRecords()).orElse(Lists.newArrayList());

        List<Integer> userIdList = Lists.newArrayList();
        List<Integer> channelIdList = Lists.newArrayList();
        List<Integer> channelCarrierIdList = Lists.newArrayList();
        List<Integer> channelPlatformIdList = Lists.newArrayList();
        userChannels.forEach(userChannel -> {
            userIdList.add(userChannel.getUserId());
            channelIdList.add(userChannel.getChannelId());
            channelCarrierIdList.add(userChannel.getChannelCarrierId());
            channelPlatformIdList.add(userChannel.getChannelPlatformId());
        });

        if (umsAdminMap.isEmpty()) {
            // 用户名 只需要从umsAdmins里取
            if (!userIdList.isEmpty()) {
                umsAdminMap = Optional.ofNullable(
                        umsAdminService.lambdaQuery()
                                .in(UmsAdmin::getId, userIdList.stream().distinct().collect(Collectors.toList()))
                                .select(UmsAdmin::getId, UmsAdmin::getUsername).list()
                ).orElse(Lists.newArrayList()).stream().collect(Collectors.toMap(UmsAdmin::getId, Function.identity()));
            }
        }
        if (channelMap.isEmpty()) {
            // 渠道名只需要从channels里取
            if (!channelIdList.isEmpty()) {
                channelMap = Optional.ofNullable(channelService.lambdaQuery()
                        .in(Channel::getId, channelIdList.stream().distinct().collect(Collectors.toList()))
                        .select(Channel::getId, Channel::getChannelName)
                        .list()).orElse(Lists.newArrayList()).stream().collect(Collectors.toMap(Channel::getId, Function.identity()));
            }
        }
        Map<Integer, ChannelCarrier> channelCarrierMap = Maps.newHashMap();
        if (!channelCarrierIdList.isEmpty()) {
            channelCarrierMap = Optional.ofNullable(
                    channelCarrierService.lambdaQuery()
                            .in(ChannelCarrier::getId, channelCarrierIdList.stream().distinct().collect(Collectors.toList()))
                            .select(ChannelCarrier::getId, ChannelCarrier::getChannelCarrierName)
                            .list()
            ).orElse(Lists.newArrayList()).stream().collect(Collectors.toMap(ChannelCarrier::getId, Function.identity()));
        }
        Map<Integer, ChannelPlatform> channelPlatformMap = Maps.newHashMap();
        if (!channelPlatformIdList.isEmpty()) {
            channelPlatformMap = Optional.ofNullable(channelPlatformService.lambdaQuery()
                    .in(ChannelPlatform::getId, channelPlatformIdList.stream().distinct().collect(Collectors.toList()))
                    .select(ChannelPlatform::getId, ChannelPlatform::getChannelPlatformName)
                    .list()).orElse(Lists.newArrayList()).stream().collect(Collectors.toMap(ChannelPlatform::getId, Function.identity()));
        }
        List<UserChannelPageVO> userChannelPageVOS = Lists.newArrayList();
        for (UserChannel userChannel : userChannels) {
            userChannelPageVOS.add(new UserChannelPageVO().setId(userChannel.getId())
                    .setUserName(Optional.ofNullable(umsAdminMap.get(userChannel.getUserId())).orElse(new UmsAdmin()).getUsername())
                    .setChannelName(Optional.ofNullable(channelMap.get(userChannel.getChannelId())).orElse(new Channel()).getChannelName())
                    .setChannelCarrierName(Optional.ofNullable(channelCarrierMap.get(userChannel.getChannelCarrierId())).orElse(new ChannelCarrier()).getChannelCarrierName())
                    .setChannelPlatformName(Optional.ofNullable(channelPlatformMap.get(userChannel.getChannelPlatformId())).orElse(new ChannelPlatform()).getChannelPlatformName())
                    .setIsBest(userChannel.getIsBest())
                    .setPlatformRate(userChannel.getPlatformRate())
                    .setPrice(userChannel.getPrice())
                    .setRate(userChannel.getRate())
            );
        }
        return CommonResult.success(CommonPage.restPage(
                new Page<UserChannelPageVO>()
                        .setTotal(userChannelPageList.getTotal())
                        .setSize(userChannelPageList.getSize())
                        .setCurrent(userChannelPageList.getCurrent())
                        .setRecords(userChannelPageVOS)));
    }
}
